<?php

/**
 * Description of AutoSocialShare
 *
 * @version  1.0 $Id: pingfmk2.php 4 2012-02-24 09:24:56Z webbochsant@gmail.com $
 * @author Daniel Eliasson (joomla at stilero.com)
 * @copyright  (C) 2012-jan-19 Stilero Webdesign http://www.stilero.com
 * @category Plugins
 * @license	GPLv2
 * 
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * 
 * This file is part of AutoSocialShare.
 * 
 * AutoSocialShare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * AutoSocialShare is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with AutoSocialShare.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

// import library dependencies
jimport('joomla.plugin.plugin');

class plgk2Pingfmk2 extends JPlugin {

    var $config;
    var $errorOccured;

    function plgk2Pingfmk2(&$subject, $config) {
        parent::__construct($subject, $config);
        $language = JFactory::getLanguage();
        $language->load('plg_k2_pingfmk2', JPATH_ADMINISTRATOR, 'en-GB', true);
        $language->load('plg_k2_pingfmk2', JPATH_ADMINISTRATOR, null, true);
        $this->errorOccured = FALSE;
        $this->config = array(
            'shareLogTableName'     =>      '#__autopingfmk2_log',
            'pluginLangPrefix'      =>      'PLG_K2_PINGFM_',
            'extType'               =>      'k2',
            'username'              =>      $this->params->def('username'),
            'password'              =>      $this->params->def('password'),
            'contrClass'            =>      'PingControllerClass',
            'shareContrClass'       =>      'stlShareControllerClass',
            'basicPingFMClass'      =>      'basicPingFMClass',
            'articleClass'          =>      'Article',
            'classFolder'           =>      'pingfmclasses',
            'categoriesToShare'     =>      $this->params->def('section_id'),
            'shareDelay'            =>      $this->params->def('delay'),
            'articlesNewerThan'     =>      $this->params->def('items_newer_than'),
            'serviceToUse'          =>      $this->params->def('use_pingservice')
        );            
    }
    public function onAfterK2Save( &$item, $isNew ) {
        $this->inBackend = true;
        $this->initPing($item);
        $this->sendPing();
        return;   
    }

    public function onK2AfterDisplayContent( & $item, & $params, $limitstart) {
        $this->inBackend = false;
        $this->initPing($item);
        $this->sendPing();
        return;  
    }
    
    public function sendPing() {
        if( !$this->isInitialChecksOK() ) {
            $this->displayMessage(JText::_($this->CheckClass->error['message']) , $this->CheckClass->error['type']);
            return;
        }
        if ($this->CheckClass->shareToPingFM() ) {
            $fullMessage = urldecode($this->CheckClass->fullMessage);
            $this->displayMessage(JText::_('Shared: ').$fullMessage);
            return;
        }else{
            $this->displayMessage(JText::_($this->CheckClass->error['message']) , $this->CheckClass->error['type']);
            return;
        }
    }
    
    private function displayMessage($msg, $messageType = "") {
        $isSetToDisplayMessages = ($this->params->def('pingmessages')==0)?false:true;
        if( ! $isSetToDisplayMessages || ! $this->inBackend ){
            return;
        }else{
            JFactory::getApplication()->enqueueMessage( $msg, $messageType);
        }
    }
    
    private function initPing($article){
        $this->loadClasses();
        $this->initClasses();
        $Article = new Article($article, $this->config['extType']);
        $this->CheckClass->setArticleObject($Article);
    }
    
    private function loadClasses() {
        $classFolder = $this->config['classFolder'];
        $contrClass = $this->config['contrClass'];
        $shareContrClass = $this->config['shareContrClass'];
        $basicPingFMClass = $this->config['basicPingFMClass'];
        JLoader::register($contrClass, dirname(__FILE__).DS.$classFolder.DS.$contrClass.'.php');
        JLoader::register($shareContrClass, dirname(__FILE__).DS.$classFolder.DS.$shareContrClass.'.php');
        JLoader::register($basicPingFMClass, dirname(__FILE__).DS.$classFolder.DS.$basicPingFMClass.'.php');
        JLoader::register($this->config['articleClass'], dirname(__FILE__).DS.$classFolder.DS.strtolower($this->config['articleClass']).'.php');
    }
    
    private function initClasses(){
        $this->CheckClass = new $this->config['contrClass']( 
            array(
            'username'              =>      $this->config['username'],
            'password'              =>      $this->config['password'],
            'serviceToUse'          =>      $this->config['serviceToUse'],
            'shareLogTableName'     =>      $this->config['shareLogTableName'],
            'pluginLangPrefix'      =>      $this->config['pluginLangPrefix'],
            'categoriesToShare'     =>      $this->config['categoriesToShare'],
            'shareDelay'            =>      $this->config['shareDelay'],
            'articlesNewerThan'     =>      $this->config['articlesNewerThan'],
            )
        );
    }
    
    private function doInitialChecks() {
        $this->CheckClass->isServerSupportingRequiredFunctions();
        $this->CheckClass->isServerSafeModeDisabled();
        $this->CheckClass->isLoginDetailsEntered();
        $this->CheckClass->isArticleObjectIncluded();
        $this->CheckClass->isItemActive();
        $this->CheckClass->isItemPublished();
        $this->CheckClass->isItemNewEnough();
        $this->CheckClass->isItemPublic();
        $this->CheckClass->isCategoryToShare();
        $this->CheckClass->prepareTables();
        $this->CheckClass->isSharingToEarly();
        $this->CheckClass->isItemAlreadyShared();
        return $this->CheckClass->error;
    }
        
    private function isInitialChecksOK() {
        $errorMessage = $this->doInitialChecks();
        if ( $errorMessage != FALSE ) {
            return FALSE;
        }
        return TRUE;
    }
    
//    private function getArticleObjectFromJoomlaArticle($joomlaArticle) {
//        $articleObject = new stdClass();
//        $articleObject->id = $joomlaArticle->id;
//        $articleObject->language= (isset($joomlaArticle->language))?$joomlaArticle->language:"";
//        $articleObject->link = $joomlaArticle->alias;
//        $articleObject->full_url = $this->getFullURL($joomlaArticle->id);
//        $articleObject->tags = $this->getArticleTagsArray($joomlaArticle->metakey);
//        $articleObject->title = $joomlaArticle->title;
//        $articleObject->catid = (isset($joomlaArticle->catid))?$joomlaArticle->catid:0;
//        $articleObject->access = $joomlaArticle->access;
//        $articleObject->publish_up = $joomlaArticle->publish_up;
//        $articleObject->published = $joomlaArticle->state; 
//        return $articleObject;
//    }
//    
//    private function getFullURL($articleID) {
//        $urlQuery = "?option=com_content&view=article&id=".$articleID;
//        $fullURL = JURI::root()."index.php".$urlQuery;
//        return $fullURL;
//    }
//    
//    private function getArticleTagsArray($commaSpearatedMetaKeys) {
//        if($commaSpearatedMetaKeys == ""){
//            return;
//        }
//       $metaKeyArray = explode(",", $commaSpearatedMetaKeys);
//       foreach ($metaKeyArray as $key => $value) {
//           $tagsArray[] = trim(str_replace(" ", "", $value));
//       }
//       return $tagsArray;
//    }
}

//End Class